/**
 * 搜索页面
 * 提供全局搜索功能，支持搜索各种内容类型
 * @author WeChat Mini Program Team
 * @since 2025-08-14
 */

const Router = require('../../utils/router')
const Storage = require('../../utils/storage')
const Logger = require('../../utils/logger')
const Track = require('../../utils/track')

const { CommunityService, TeacherService, BuddyService, SwapService } = require('../../services/index')

const SEARCH_HISTORY_KEY = 'searchHistory';
const MAX_HISTORY_COUNT = 20;

Page({
  data: {
    // 搜索类型和关键词
    searchType: 'all', // all, good-deeds, teachers, courses, buddies, items
    keyword: '',
    placeholder: '搜索内容...',
    
    // 搜索状态
    hasSearched: false,
    isLoading: false,
    showSuggestions: false,
    
    // 搜索历史和热词
    searchHistory: [],
    hotKeywords: [],
    suggestions: [],
    
    // 搜索结果
    results: {
      goodDeeds: [],
      teachers: [],
      courses: [],
      buddies: [],
      items: []
    },
    resultTabs: [],
    currentTab: 'all',
    totalCount: 0,
    page: 1,
    hasMore: false
  },

  onLoad(options) {
    Logger.info('Search page loaded', options)
    Track.trackPageView('/pages/search/index', options)
    
    // 设置搜索类型和占位符
    if (options.type) {
      const typeConfig = this.getTypeConfig(options.type)
      this.setData({
        searchType: options.type,
        currentTab: options.type,
        placeholder: typeConfig.placeholder
      })
    }
    
    // 设置初始关键词
    if (options.keyword) {
      this.setData({ keyword: options.keyword })
      this.performSearch()
    }
    
    this.loadSearchHistory()
    this.loadHotKeywords()
  },

  // 获取类型配置
  getTypeConfig(type) {
    const configs = {
      'all': { placeholder: '搜索内容...', name: '全部' },
      'good-deeds': { placeholder: '搜索好人好事...', name: '好人好事' },
      'teachers': { placeholder: '搜索教师...', name: '教师' },
      'courses': { placeholder: '搜索课程...', name: '课程' },
      'buddies': { placeholder: '搜索搭子活动...', name: '搭子' },
      'items': { placeholder: '搜索闲置物品...', name: '物品' }
    };
    return configs[type] || configs['all'];
  },

  // 输入关键词
  onKeywordInput(e) {
    const keyword = e.detail.value;
    this.setData({ keyword });
    
    if (keyword.trim()) {
      this.getSuggestions(keyword);
    } else {
      this.setData({ 
        showSuggestions: false,
        suggestions: []
      });
    }
  },

  // 清空关键词
  clearKeyword() {
    this.setData({
      keyword: '',
      showSuggestions: false,
      suggestions: [],
      hasSearched: false
    });
  },

  // 执行搜索
  async onSearch() {
    const keyword = this.data.keyword.trim()
    if (!keyword) {
      wx.showToast({ title: '请输入搜索关键词', icon: 'none' })
      return
    }
    
    Track.trackSearch(keyword, this.data.searchType, 0)
    
    // 保存搜索历史
    this.saveSearchHistory(keyword)
    
    // 重置搜索结果
    this.setData({
      results: {
        goodDeeds: [],
        teachers: [],
        courses: [],
        buddies: [],
        items: []
      },
      page: 1,
      hasSearched: true,
      showSuggestions: false
    })
    
    await this.performSearch()
  },

  // 执行实际搜索
  async performSearch() {
    if (this.data.isLoading) return;
    
    const { keyword, searchType, page } = this.data;
    
    try {
      this.setData({ isLoading: true });
      
      let searchPromises = [];
      let resultTabs = [];
      
      // 根据搜索类型执行不同的搜索
      if (searchType === 'all') {
        // 全部搜索
        searchPromises = [
          this.searchGoodDeeds(keyword, page),
          this.searchTeachers(keyword, page),
          this.searchCourses(keyword, page),
          this.searchBuddies(keyword, page),
          this.searchItems(keyword, page)
        ];
      } else {
        // 特定类型搜索
        switch (searchType) {
          case 'good-deeds':
            searchPromises = [this.searchGoodDeeds(keyword, page)];
            break;
          case 'teachers':
            searchPromises = [this.searchTeachers(keyword, page)];
            break;
          case 'courses':
            searchPromises = [this.searchCourses(keyword, page)];
            break;
          case 'buddies':
            searchPromises = [this.searchBuddies(keyword, page)];
            break;
          case 'items':
            searchPromises = [this.searchItems(keyword, page)];
            break;
        }
      }
      
      const results = await Promise.all(searchPromises);
      
      // 处理搜索结果
      this.processSearchResults(results);
      
    } catch (error) {
      console.error('搜索失败:', error);
      wx.showToast({ title: '搜索失败', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  // 搜索好人好事
  async searchGoodDeeds(keyword, page = 1) {
    try {
      const response = await CommunityService.searchGoodDeeds({
        keyword,
        page,
        limit: 10
      })
      
      if (response.success && response.data) {
        const items = response.data.items.map(item => ({
          ...item,
          createTimeFormatted: this.formatRelativeTime(item.created_at)
        }))
        
        return {
          type: 'goodDeeds',
          name: '好人好事',
          items,
          hasNext: response.data.has_next,
          count: response.data.total || items.length
        }
      }
    } catch (error) {
      Logger.error('搜索好人好事失败:', error)
    }
    
    return { type: 'goodDeeds', name: '好人好事', items: [], hasNext: false, count: 0 }
  },

  // 搜索教师
  async searchTeachers(keyword, page = 1) {
    try {
      const response = await TeacherService.searchTeachers({
        keyword,
        page,
        limit: 10
      })
      
      if (response.success && response.data) {
        return {
          type: 'teachers',
          name: '教师',
          items: response.data.items || [],
          hasNext: response.data.has_next,
          count: response.data.total || 0
        }
      }
    } catch (error) {
      Logger.error('搜索教师失败:', error)
    }
    
    return { type: 'teachers', name: '教师', items: [], hasNext: false, count: 0 }
  },

  // 搜索课程
  async searchCourses(keyword, page = 1) {
    try {
      const response = await TeacherService.searchCourses({
        keyword,
        page,
        limit: 10
      })
      
      if (response.success && response.data) {
        const items = response.data.items.map(item => ({
          ...item,
          startTimeFormatted: this.formatRelativeTime(item.start_time)
        }))
        
        return {
          type: 'courses',
          name: '课程',
          items,
          hasNext: response.data.has_next,
          count: response.data.total || items.length
        }
      }
    } catch (error) {
      Logger.error('搜索课程失败:', error)
    }
    
    return { type: 'courses', name: '课程', items: [], hasNext: false, count: 0 }
  },

  // 搜索搭子
  async searchBuddies(keyword, page = 1) {
    try {
      const response = await BuddyService.searchPosts({
        keyword,
        page,
        limit: 10
      })
      
      if (response.success && response.data) {
        const items = response.data.posts.map(item => ({
          ...item,
          createTimeFormatted: this.formatRelativeTime(item.created_at)
        }))
        
        return {
          type: 'buddies',
          name: '搭子',
          items,
          hasNext: response.data.has_next,
          count: response.data.total || items.length
        }
      }
    } catch (error) {
      Logger.error('搜索搭子失败:', error)
    }
    
    return { type: 'buddies', name: '搭子', items: [], hasNext: false, count: 0 }
  },

  // 搜索物品
  async searchItems(keyword, page = 1) {
    try {
      const response = await SwapService.searchItems({
        keyword,
        page,
        limit: 10
      })
      
      if (response.success && response.data) {
        const items = response.data.items.map(item => ({
          ...item,
          statusText: this.getStatusText(item.status)
        }))
        
        return {
          type: 'items',
          name: '物品',
          items,
          hasNext: response.data.has_next,
          count: response.data.total || items.length
        }
      }
    } catch (error) {
      Logger.error('搜索物品失败:', error)
    }
    
    return { type: 'items', name: '物品', items: [], hasNext: false, count: 0 }
  },

  // 处理搜索结果
  processSearchResults(results) {
    const { page } = this.data;
    let newResults = { ...this.data.results };
    let resultTabs = [];
    let totalCount = 0;
    let hasMore = false;
    
    results.forEach(result => {
      if (result && result.items) {
        if (page === 1) {
          newResults[result.type] = result.items;
        } else {
          newResults[result.type] = [...newResults[result.type], ...result.items];
        }
        
        if (result.count > 0) {
          resultTabs.push({
            type: result.type,
            name: result.name,
            count: result.count
          });
        }
        
        totalCount += result.count;
        if (result.hasNext) hasMore = true;
      }
    });
    
    // 添加全部标签
    if (this.data.searchType === 'all' && resultTabs.length > 1) {
      resultTabs.unshift({
        type: 'all',
        name: '全部',
        count: totalCount
      });
    }
    
    this.setData({
      results: newResults,
      resultTabs,
      totalCount,
      hasMore
    });
  },

  // 获取搜索建议
  async getSuggestions(keyword) {
    try {
      // 这里可以调用后端API获取搜索建议
      // 暂时使用模拟数据
      const mockSuggestions = [
        keyword + '教师',
        keyword + '课程',
        keyword + '活动',
        keyword + '社区'
      ].filter(item => item.length > 1);
      
      this.setData({
        suggestions: mockSuggestions.slice(0, 5),
        showSuggestions: mockSuggestions.length > 0
      });
    } catch (error) {
      console.error('获取搜索建议失败:', error);
    }
  },

  // 选择建议
  selectSuggestion(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      keyword,
      showSuggestions: false
    });
    this.onSearch();
  },

  // 选择关键词
  selectKeyword(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({ keyword });
    this.onSearch();
  },

  // 切换结果标签
  switchResultTab(e) {
    const currentTab = e.currentTarget.dataset.type;
    this.setData({ currentTab });
  },

  // 加载搜索历史
  loadSearchHistory() {
    const history = Storage.get(SEARCH_HISTORY_KEY, [])
    this.setData({ searchHistory: history })
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = Storage.get(SEARCH_HISTORY_KEY, [])
    
    // 移除重复项
    history = history.filter(item => item !== keyword)
    
    // 添加到开头
    history.unshift(keyword)
    
    // 限制数量
    if (history.length > MAX_HISTORY_COUNT) {
      history = history.slice(0, MAX_HISTORY_COUNT)
    }
    
    Storage.set(SEARCH_HISTORY_KEY, history)
    this.setData({ searchHistory: history })
  },

  // 删除单个历史记录
  deleteHistory(e) {
    const keyword = e.currentTarget.dataset.keyword
    let history = this.data.searchHistory.filter(item => item !== keyword)
    
    Storage.set(SEARCH_HISTORY_KEY, history)
    this.setData({ searchHistory: history })
  },

  // 清空搜索历史
  clearHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          Storage.remove(SEARCH_HISTORY_KEY)
          this.setData({ searchHistory: [] })
        }
      }
    })
  },

  // 加载热门关键词
  async loadHotKeywords() {
    try {
      // 这里可以调用后端API获取热门关键词
      // 暂时使用模拟数据
      const hotKeywords = [
        '社区活动', '志愿服务', '党建学习', '教师培训',
        '好人好事', '互助交流', '物品交换', '搭子活动'
      ];
      
      this.setData({ hotKeywords });
    } catch (error) {
      console.error('加载热门关键词失败:', error);
    }
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'available': '可交换',
      'pending': '交换中',
      'exchanged': '已交换',
      'unavailable': '不可用'
    };
    return statusMap[status] || '未知';
  },

  // 跳转到详情页
  goToGoodDeedDetail(e) {
    const id = e.currentTarget.dataset.id
    Track.trackClick('search_result_good_deed', 'link', { id })
    Router.navigateTo('/pages/community/education/good-deeds/detail', { id })
  },

  goToTeacherDetail(e) {
    const id = e.currentTarget.dataset.id
    Track.trackClick('search_result_teacher', 'link', { id })
    Router.navigateTo('/pages/teacher/detail/detail', { id })
  },

  goToCourseDetail(e) {
    const id = e.currentTarget.dataset.id
    Track.trackClick('search_result_course', 'link', { id })
    Router.navigateTo('/pages/teacher/courses/detail', { id })
  },

  goToBuddyDetail(e) {
    const id = e.currentTarget.dataset.id
    Track.trackClick('search_result_buddy', 'link', { id })
    Router.navigateTo('/pages/buddy/post/detail', { id })
  },

  goToItemDetail(e) {
    const id = e.currentTarget.dataset.id
    Track.trackClick('search_result_item', 'link', { id })
    Router.navigateTo('/pages/swap/item/detail', { id })
  },

  // 工具方法：格式化相对时间
  formatRelativeTime(dateString) {
    if (!dateString) return ''
    
    const date = new Date(dateString)
    const now = new Date()
    const diff = now - date
    
    const minute = 60 * 1000
    const hour = minute * 60
    const day = hour * 24
    const month = day * 30
    
    if (diff < minute) {
      return '刚刚'
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前'
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前'
    } else if (diff < month) {
      return Math.floor(diff / day) + '天前'
    } else {
      return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    }
  },

  // 上拉加载更多
  async onReachBottom() {
    if (!this.data.hasMore || this.data.isLoading || !this.data.hasSearched) {
      return
    }

    this.setData({
      page: this.data.page + 1
    })
    
    await this.performSearch()
  }
})
